package com.example.auth3.config;

import com.example.auth3.util.DfUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * 资源服务器
 * @author shangSshang
 * 2018.12.21 12:00:03
 */
@Slf4j
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
	private   static final Logger logger = LoggerFactory.getLogger(ResourceServerConfiguration.class);

    @Value("#{'${myapp.whiteList}'.split(',')}")
    private String[] whiteList;
    @Value("#{'${myapp.resourceList}'.split(',')}")
    private String[] resourceList;


	/**
	 * 重写自定义配置拦截
	 * @param http
	 * @throws Exception
	 */
	@Override
	public void configure(HttpSecurity http) throws Exception {


/*

        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
//                    .and()
//                    .requestMatchers().anyRequest()
                .and()
//                .anonymous().disable()
//		.requestMatchers().antMatchers("/login","/index")
//		.and()
                //authorizeRequests。antMatchers.permitAll() "/login","/index" 配置放过 登录验证 切线 拦截
                //"/js/**","/css/**","/fonts/**","/images/**" 放过资源加载验证
                .authorizeRequests()
//                .anyRequest()
		.antMatchers( DfUtils.arrayList(whiteList,resourceList))
//		.antMatchers("/login","/index","/js/**","/css/**","/fonts/**","/images/**")
//		.antMatchers("/login/**")
                .permitAll()
                // 其他配置拦截权限
                .anyRequest().authenticated()
		.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
*/
		logger.info("资源拦截权限");

		http
				//加载自定义的oauth2 授权信息判断
				.requestMatcher(new OAuth2RequestedMatcher())
				.authorizeRequests()
				// 放开权限的 静态资源URL
				.antMatchers( DfUtils.arrayList(whiteList,resourceList)).permitAll() // 放开权限的url
				.anyRequest().authenticated();
	}
	/**
	 * 判断来源请求是否包含oauth2授权信息<br>
	 * url参数中含有access_token,或者header里有Authorization
	 */
	private static class OAuth2RequestedMatcher implements RequestMatcher {
		@Override
		public boolean matches(HttpServletRequest request) {
			// 请求参数中包含access_token参数
			if (request.getParameter(OAuth2AccessToken.ACCESS_TOKEN) != null) {
				return true;
			}

			// 头部的Authorization值以Bearer开头
			String auth = request.getHeader("Authorization");
			if (auth != null) {
				return auth.startsWith(OAuth2AccessToken.BEARER_TYPE);
			}

			return false;
		}
	}
}